<template>
    <!-- 搜索框 -->
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
        <el-form-item label="课程ID">
            <el-input v-model="queryInfo.id" placeholder="请输入ID" clearable />
        </el-form-item>
        <el-form-item label="课程名称">
            <el-input v-model="queryInfo.courseName" placeholder="请输入课程名称关键字" clearable />
        </el-form-item>
        <el-form-item label="课程类型">
            <el-select v-model="queryInfo.typeId" placeholder="请选择课程类型" clearable>
                <el-option 
                    v-for="item in courseTypes"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
            </el-select>
        </el-form-item>
        <el-form-item label="咨询师">
            <el-select v-model="queryInfo.teacherId" placeholder="请选择咨询师" clearable>
                <el-option 
                    v-for="item in consults"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
            </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button type="success" @click="onAdd">添加课程信息</el-button>
      </el-form-item>
    </el-form>
    <!-- 信息展览 -->
    <el-table :data="tableData" stripe style="width: 100%">
    <!-- <el-table-column prop="id" label="id" width="50" /> -->
    
    <el-table-column prop="id" label="课程ID" width="120" />
    <el-table-column prop="courseName" label="课程名称" width="150" />
    <el-table-column prop="tabularChart" label="列表图" width="120" >
        <template #default="scope">
            <!-- {{ scope.row.tabularChart }} -->
            <el-image style="width: 100px; height: 100px" :src="url+scope.row.tabularChart" :fit="fit" />   
        </template>
    </el-table-column>
    <el-table-column prop="courseTime" label="课程时长" width="120" />
    <el-table-column prop="courseMount" label="课件数量" width="120" />
    <el-table-column prop="courseIntroduce" label="课程简介" width="150" />
    <el-table-column prop="applicablePopulation" label="适用人群" width="150" />
    <el-table-column prop="courseType.name" label="课程分类" width="200" />
    <el-table-column prop="learnHarvest" label="学习收获" width="120" />
    <el-table-column prop="subscriptionNotice" label="订阅须知" width="120" />
    <el-table-column prop="collects" label="收藏量" width="120" />
    <el-table-column prop="consult.name" label="咨询师" width="120" />
    <el-table-column prop="courseVideo" label="课程视频" width="120">
        <template #default="scope">
            <!-- <video width="500px" height="200px" controls>
                <source :src="url+scope.row.courseVideo" type="video/mp4"> 
            </video> -->
            <!-- 触发视频预览的按钮 -->
             <!-- {{ scope.row.courseVideo }} -->
            <el-button type="primary" @click="openVideoPreview(scope.row.courseVideo)">预览视频</el-button>
            <!-- 视频预览对话框 -->
            <el-dialog
                v-model="isVideoPreviewVisible"
                :append-to-body="true"
                :before-close="handleClose"
                class="fullscreen-dialog"   
            >
            <template #title>视频预览</template>
            <video ref="videoref" width="100%" height="100%" controls>
                <source :src="videoSrc" type="video/mp4">
            </video>
            </el-dialog>
      </template>
    </el-table-column>
    <el-table-column prop="originalPrice" label="原始价格" width="120" />
    <el-table-column prop="discountPrice" label="折扣价格" width="120" />
    <el-table-column prop="validityPeriod" label="有效期" width="80" />
    <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
            <el-button link type="primary" size="small" @click="toEdit(scope.row)">修改</el-button>
            <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
        </template>
    </el-table-column>
  </el-table>
   <!-- 分页 -->
   <el-pagination
        style="margin-top: 20px;"
        v-model:current-page="queryInfo.pageNum"
        v-model:page-size="queryInfo.pageSize"
        :page-sizes="[2, 5, 10, 20]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />

        <!-- <el-dialog v-model="saveOrupdateVisible" :title="saveOrupdatetitle" width="500"/> -->
        <el-dialog v-model="saveOrupdateVisible" :title="saveOrupdatetitle" width="500" :show-close="false">
            <el-form :model="course">
                <el-form-item label="课程名称" :label-width="formLabelWidth">
                    <el-input v-model="course.courseName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="课程封面" :label-width="formLabelWidth">
                    <!-- <el-input v-model="course.tabularChart" autocomplete="off" /> -->
                    <el-upload
                        v-model:file-list="fileList"
                        action= "http://localhost:8080/file/upload"
                        :on-success="handleAvatarSuccess"
                        :show-file-list="true"
                        list-type="picture-card"
                    >
                       
                        <el-icon ><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="课程时长" :label-width="formLabelWidth">
                    <el-input v-model="course.courseTime" autocomplete="off" />
                </el-form-item>
                <el-form-item label="课件数量" :label-width="formLabelWidth">
                    <el-input v-model="course.courseMount" autocomplete="off" />
                </el-form-item>
                <el-form-item label="课程简介" :label-width="formLabelWidth">
                    <el-input v-model="course.courseIntroduce" autocomplete="off" />
                </el-form-item>
                <el-form-item label="适用人群" :label-width="formLabelWidth">
                    <el-input v-model="course.applicablePopulation" autocomplete="off" />
                </el-form-item>
                <el-form-item label="课程分类" :label-width="formLabelWidth">
                    <el-select v-model="course.typeId" placeholder="请选择课程类型" clearable>
                        <el-option 
                            v-for="item in courseTypes"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="学习收获" :label-width="formLabelWidth">
                    <el-input v-model="course.learnHarvest" autocomplete="off" />
                </el-form-item>
                <el-form-item label="订阅须知" :label-width="formLabelWidth">
                    <el-input v-model="course.subscriptionNotice" autocomplete="off" />
                </el-form-item>
                <el-form-item label="收藏数量" :label-width="formLabelWidth">
                    <el-input v-model="course.collects" autocomplete="off" />
                </el-form-item>
                <el-form-item label="咨询老师" :label-width="formLabelWidth">
                    <el-select v-model="course.teacherId" placeholder="请选择咨询师" clearable>
                        <el-option 
                            v-for="item in consults"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="课程视频" :label-width="formLabelWidth">
                    <!-- <el-input v-model="course.courseVideo" autocomplete="off" /> -->
                    <el-upload
                        v-model:file-list="videoFileList"
                        action="http://localhost:8080/file/upload" 
                        :on-success="handleVideoSuccess"
                        :before-upload="beforeUploadVideo"
                        :show-file-list="true"
                        list-type="picture-card"
                        accept="video/*"
                    >
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="原始价格" :label-width="formLabelWidth">
                    <el-input v-model="course.originalPrice" autocomplete="off" />
                </el-form-item>
                <el-form-item label="折扣价格" :label-width="formLabelWidth">
                    <el-input v-model="course.discountPrice" autocomplete="off" />
                </el-form-item>
                <el-form-item label="有效日期" :label-width="formLabelWidth">
                    <el-input v-model="course.validityPeriod" autocomplete="off" />
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="close">取消</el-button>
                    <el-button type="primary" @click="saveOrUpdate">
                        {{saveOrupdateType}}
                    </el-button>
                </div>
            </template>
        </el-dialog>
  </template>
  
<script setup>

import { nextTick, onMounted,reactive,ref } from 'vue'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
const tableData = ref([])
//   定义一个方法当页面加载时就调用
  onMounted(() => {
    getList();
    courseTypeList();
    consultList();
    // tableData.value = res.data.sort((a, b) => a.id - b.id);
  })
//   定义一个全局参数变量
const queryInfo = ref({
    pageNum: 1,
    pageSize: 5,
    id:'',
    courseName: '',
    tabularChart: '',
    courseTime: '',
    courseMount: '',
    courseIntroduce: '',
    applicablePopulation: '',
    typeId: '',
    learnHarvest: '',
    subscriptionNotice: '',
    collects: '',
    teacherId: '',
    courseVideo: '',
    originalPrice: '',
    discountPrice: '',
    validityPeriod: ''
    
})


//图片和视频
//图片
const fit = ref('cover')
const url = ref('http://localhost:8080/file/downLoad?fileName=')


//视频
const isVideoPreviewVisible = ref(false);
const videoSrc = ref('');
const videoref = ref(null);

const openVideoPreview = (videoPath) => {
  isVideoPreviewVisible.value = true; // 先打开对话框
  document.body.style.overflow = "hidden";

  // **清空 videoSrc，强制 Vue 监听到变化**
  videoSrc.value = ""; 
  nextTick(() => {
    videoSrc.value = url.value + videoPath;
    // console.log("open " + videoSrc.value);

    nextTick(() => {
      if (videoref.value) {
        videoref.value.load(); // **强制重新加载视频**
      }
    });
  });
};
const handleClose = () => {
  
  if (videoref.value) {
    videoref.value.pause();
    videoref.value.currentTime = 0;
  }
  videoSrc.value = ""; // 确保视频路径清空
  isVideoPreviewVisible.value = false;
  document.body.style.overflow = "auto";
//   console.log("close：  " + videoSrc.value);
};

//视频上传
const videoFileList = ref([]);
const handleVideoSuccess = (response, uploadFile) => {
    console.log("上传成功，后端返回：", response);
    course.value.courseVideo = response.data; // 假设后端返回视频的URL
};
//限制上传大小
const beforeUploadVideo = (file) => {
    const isLt50M = file.size / 1024 / 1024 < 50;
    if (!isLt50M) {
        ElMessage.error('上传视频大小不能超过 50MB!');
    }
    return isLt50M;
};
//


// //图片上传
let fileList = ref([])
const imageUrl = ref(true)
const handleAvatarSuccess= (response,uploadFile) => {
  console.log(response);
  console.log(uploadFile);
  //赋值
  course.value.tabularChart = response.data

}

//   定义一个方法，用于获取课程列表
const getList = () => {
// 使用axios调用后端接口获取数据
    axios.get('/course/selectAll',{
        params: queryInfo.value
    })
    .then((resp) => {
        let result = resp.data // 后端返回的数据
        if (result.code == 1) {
        total.value = result.data.total
        tableData.value = result.data.list
        }else{
        ElMessage.error('获取课程列表失败')
        }
    })
}
//定义一个数组，用于存放课程分类的集合
const courseTypes = ref([])
//定义一个方法，来查询所有的课程分类集合
const courseTypeList = () =>{
    axios.get('/courseType/selectAll')
    .then((resp) => {
        let result = resp.data // 后端返回的数据    
        if (result.code == 1) {
           //想要把id作为数组下标，name作为value值
           courseTypes.value = result.data.list
           console.log(courseTypes.value);             
        }else{
            ElMessage.error('获取课程分类列表失败')
        }
        
    })
}
//定义一个数组，用于存放课程分类的集合
const consults = ref([])
//定义一个方法，来查询所有的课程分类集合
const consultList = () =>{
    axios.get('/consult/selectAll')
    .then((resp) => {
        let result = resp.data // 后端返回的数据    
        if (result.code == 1) {
           //想要把id作为数组下标，name作为value值
           consults.value = result.data.list
           console.log(consults.value);             
        }else{
            ElMessage.error('获取课程分类列表失败')
        }
        
    })
}
// 分页
// 分页操作
// 定义一个数据总条数
const total = ref(0)
const handleSizeChange = (val) => {
  queryInfo.value.pageSize = val;
  queryInfo.value.pageNum = 1;
  getList();
}
const handleCurrentChange = (val) => {
  queryInfo.value.pageNum = val;
  getList();
}

//  添加和修改方法使用同一个弹窗
//   定义变量，用于保存添加或修改的标题
const saveOrupdatetitle = ref('')
//   定义变量，用于保存添加或修改的对话框是否显示
const saveOrupdateVisible=ref(false);
//   定义变量，用于修改弹出框确认类型
const saveOrupdateType = ref('')
//   定义对象，存放课程信息字段
const course = ref({
    id:0,
    courseName: '',
    tabularChart: '',
    courseTime: '',
    courseMount: '',
    courseIntroduce: '',
    applicablePopulation: '',
    typeId: '',
    learnHarvest: '',
    subscriptionNotice: '',
    collects: '',
    teacherId: '',
    courseVideo: '',
    originalPrice: '',
    discountPrice: '',
    validityPeriod: ''
})


//1.修改课程信息方法
const toEdit = row => {
    saveOrupdatetitle.value = '修改课程信息'
    saveOrupdateVisible.value = true
    saveOrupdateType.value = '确认修改'
    course.value = row
    //把图片的名称和路径放入到filelist中
    fileList.value = [{
        name: course.value.tabularChart,
        url: url.value + course.value.tabularChart 
    }]
    
}


//2.添加课程信息方法

//   定义一个方法，用于添加课程信息
const onAdd = row => {
    saveOrupdatetitle.value = '添加课程信息'
    saveOrupdateVisible.value = true
    saveOrupdateType.value = '确认添加'
    course.value = {
        courseName:''
    }
}
//3.弹出框方法
//   定义一个方法，用于关闭对话框
const close = () => {
    saveOrupdateVisible.value = false
    imageUrl.value = '';
    fileList.value = [ ];
    course.value = {
        id:'',
        courseName: '',
        tabularChart: '',
        courseTime: '',
        courseMount: '',
        courseIntroduce: '',
        applicablePopulation: '',
        typeId: '',
        learnHarvest: '',
        subscriptionNotice: '',
        collects: '',
        teacherId: '',
        courseVideo: '',
        originalPrice: '',
        discountPrice: '',
        validityPeriod: ''
     }
}
//   定义一个方法，用于保存或修改课程信息
//   添加
const saveOrUpdate = () => {
    if (saveOrupdateType.value == '确认添加') {
        axios.post('/course/insert', course.value)
            .then((resp) => {
                let result = resp.data // 后端返回的数据
                // console.log("11111"+result);
                if (result.code == 1) {
                    getList()
                    ElMessage.success('添加课程信息成功')  
                    
                } else {
                    ElMessage.error('添加课程信息失败')
                }
            })  
    }else   {
        //修改  
        axios.put('/course/update', course.value)
        .then((resp) => {
            let result = resp.data // 后端返回的数据
            if (result.code == 1) {
                ElMessage.success('修改课程信息成功')
                getList()
            } else {
                ElMessage.error('修改课程信息失败')
            }
        })
      
    }
    saveOrupdateVisible.value = false
    //清空图片url
    course.tabularChart = ''
    course.value = {
        id:'',
        courseName: '',
        tabularChart: '',
        courseTime: '',
        courseMount: '',
        courseIntroduce: '',
        applicablePopulation: '',
        typeId: '',
        learnHarvest: '',
        subscriptionNotice: '',
        collects: '',
        teacherId: '',
        courseVideo: '',
        originalPrice: '',
        discountPrice: '',
        validityPeriod: ''
     }
}


// 删除方法
const onDel = id => {
    ElMessageBox.confirm('此操作将永久删除该课程信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',  
    })
    .then(() => {
        axios.delete('/course/'+id) 
        .then((resp) => {
            let result = resp.data // 后端返回的数据
            if (result.code == 1) {
                getList()
                ElMessage.success('删除课程信息成功')
            } else {
                ElMessage.error('删除课程信息失败')
            }
        })
    })  
}


    


  const formInline = reactive({
    user: '',
    region: '',
    date: '',
  })
  
  
  </script>
  
  <style>
  .demo-form-inline {
    margin-top: 20px;
    margin-left: 20px;
  }
  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }
  
  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }

  .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

  </style>